<?php

namespace app\index\controller;

use app\admin\library\Auth;
use app\admin\model\AdminLog;
use app\admin\model\AuthDepartment;
use app\admin\model\halt\Cate;
use app\admin\model\house\In;
use app\admin\model\Preproduct;
use app\admin\model\Purcha;
use app\admin\model\purcha\Data;
use app\admin\model\Stock;
use app\admin\model\Supplier;
use app\common\controller\Frontend;
use EasyWeChat\Factory;
use app\admin\model\Admin;
use think\Cache;
use think\Db;
use think\Hook;
use app\common\controller\Api;

class Store extends Frontend
{

    protected $noNeedLogin = '*';
    protected $noNeedRight = '*';
    protected $layout = '';
    public $user;
    public $followId=3;//工作流对应id
    public $statusArr=[9,8,7];
    public $uid="1|ZhanZhiWei|ZhangWei|LiuQianRan|HanXiaoFang";//"ZhanZhiWei|1|ZhangWei";
    public $host = '';
    public $config = [
        'corp_id' => 'wxa8333bbf9962d0e0',//企业ID
        'secret'   => 'rnvyJF7szB2yCU6zttRdjSlq5M3AYcfQtYYadPGdFKg',
    ];

    public function _initialize()
    {
        parent::_initialize();
        $Api = new Api();
        $this->config = $Api->getConfig($Api->getDefault('Store'));

        $this->auth = \app\admin\library\Auth::instance();
        if(!in_array($this->request->action(),array("login","oauth"))){
            cookie("go_back",$this->request->url(true));

        }

        if (!$this->auth->isLogin() && !in_array($this->request->action(),array("login","oauth"))){

            header("Location:".$this->request->domain().'/index/store/login');

        }
        $this->host=$this->request->scheme()."://".$this->request->host().'/';
        //$this->user=$this->auth->userid;
        $this->user['userid']=$this->auth->userid;
    }
    //组装
    function zuzhuang(){
        $ck = Db::name("githouse")->where(array("manger"=>$this->user['userid']))->find();
        if (!$ck)$this->error("没有权限");
        $preCate = Db::name("halt_cate")->field('id,pid,name')->where(array("type"=>2,"pid"=>0,'id'=>array('neq',8)))->order("id asc")->select();
        $firstCate=$preCate[0]['id'];
        $cate = Db::name("halt_cate")->field('id,pid,name')->where(array("pid"=>$firstCate))->order("id asc")->select();
        foreach ($cate as $k=>$v){
            $cate[$k]['cateArr']=Db::name("halt_cate")->field('id,pid,name')->where(array("pid"=>$v['id']))->order("id asc")->select();
        }
        $this->view->assign("preCate", $preCate);
        $this->view->assign("cate", $cate);

        return $this->view->fetch();
    }
    //库存拆分
    function chaifen(){
        $ck = Db::name("githouse")->where(array("manger"=>$this->user['userid']))->find();
        if (!$ck)$this->error("没有权限");
        $preCate = Db::name("halt_cate")->field('id,pid,name')->where(array("type"=>2,"pid"=>0,'id'=>array('neq',8)))->order("id asc")->select();
        $firstCate=$preCate[0]['id'];
        $cate = Db::name("halt_cate")->field('id,pid,name')->where(array("pid"=>$firstCate))->order("id asc")->select();
        foreach ($cate as $k=>$v){
            $cate[$k]['cateArr']=Db::name("halt_cate")->field('id,pid,name')->where(array("pid"=>$v['id']))->order("id asc")->select();
        }
        $this->view->assign("preCate", $preCate);
        $this->view->assign("cate", $cate);

        return $this->view->fetch();
    }
    function chaifens(){
        $shopid = $this->request->post('id');
        $num = $this->request->post('num');
        if ($shopid==null || $num==null)$this->error("参数错误");
        $info = Db::name("githouse")->field("id")->where(array("manger"=>$this->user['userid']))->find();
        if (!$info)$this->error("当前仓库不存在");
        $cid = $info['id'];
        $stock = Db::name("stock")->where(array("cid"=>$cid,"shopid"=>$shopid))->find();
        if (!$stock || $stock['num'] < $num)$this->error("库存不足");
        $pre = Db::name("preproduct")->field('bcp')->find($shopid);
        $bcp = explode(",",$pre['bcp']);
        foreach ($bcp as $v){
            if (Db::name("stock")->where(array("cid"=>$cid,"shopid"=>$v))->find()){
                Db::name("stock")->where(array("cid"=>$cid,"shopid"=>$v))->setInc("num",$num);
            }else{
                Db::name("stock")->insert(array("cid"=>$cid,"shopid"=>$v,"num"=>$num));
            }

        }
        Db::name("stock")->where(array("cid"=>$cid,"shopid"=>$shopid))->setDec("num",$num);
        $this->success();
    }
    function zuzhuangs(){
        $shopid = $this->request->post('id');
        $num = $this->request->post('num');
        if ($shopid==null || $num==null)$this->error("参数错误");
        $info = Db::name("githouse")->field("id")->where(array("manger"=>$this->user['userid']))->find();
        if (!$info)$this->error("当前仓库不存在");
        $cid = $info['id'];

        $pre = Db::name("preproduct")->field('bcp')->find($shopid);
        $bcp = explode(",",$pre['bcp']);
        $break=false;
        Db::startTrans();
        foreach ($bcp as $v){
            if ($info=Db::name("stock")->where(array("cid"=>$cid,"shopid"=>$v))->find()){
               if ($info['num'] < $num){
                   $break=true;
                   break;
               }else{
                   Db::name("stock")->where(array("cid"=>$cid,"shopid"=>$v))->setDec("num",$num);
               }
            }else{
                $break=true;
            }

        }
        Db::name("stock")->where(array("cid"=>$cid,"shopid"=>$shopid))->setInc("num",$num);

        if ($break){
            Db::rollback();
            $this->error("库存不足");
        }
        Db::commit();
        $this->success();
    }
    //获取成品组装
    public function getFin2()
    {
        if ($this->request->isAjax()){
            $where=[];
            $post = $_POST;

            $ck = Db::name("githouse")->where(array("manger"=>$this->user['userid']))->find();
            if (!$ck)$this->error("没有权限");
            $post['cid']=$ck['id'];
            $where['type']=2;
            if (isset($post['pid']) && $post['pid'] > 0){
                $pid = intval($post['pid']);
                $where['classif']=$pid;
            }
            $page = isset($_POST['counter']) ? intval($_POST['counter']) : 1;
            $offset = 6*($page-1);
            $info = Db::name('preproduct')->where($where)->limit($offset,6)->select();
            foreach($info as $k=>$v){
                $info[$k]['storenum']=$this->getMin($v['bcp'],$post['cid']);//$this->getStore($v['id'],$cid);
            }
            $result = array("list"=>$info);
            return json($result);
        }
    }
    //获取可以组装套数
    protected function getMin($bcp,$cid){
        if (!$bcp || !$cid)return 0;
        $bcp = explode(",",$bcp);
        $tempArr=[];
        foreach ($bcp as $v){
            if ($info = Db::name("stock")->where(array("cid"=>$cid,"shopid"=>$v))->find()){
                $tempArr[]=$info['num'];
            }else{
                $tempArr[]=0;
            }
        }
        return min($tempArr);
    }

    //获取成品拆分
    public function getFin()
    {
        if ($this->request->isAjax()){
            $where=[];
            $post = $_POST;
            $ck = Db::name("githouse")->where(array("manger"=>$this->user['userid']))->find();
            if (!$ck)$this->error("没有权限");
            $cid=$ck['id'];
            $post['cid']=$cid;
            $where['type']=2;
            if (isset($post['pid']) && $post['pid'] > 0){
                $pid = intval($post['pid']);
                $where['classif']=$pid;
            }

            if (isset($post['title']) && $post['title']!=''){
                $title = $_POST['title'];
                $where['cname']=array('like',"%{$title}%");
            }
            $page = isset($_POST['counter']) ? intval($_POST['counter']) : 1;
            $offset = 6*($page-1);
            //仓库开始
            $anywhere['cid']=$cid;
            $anywhere['num']=array('gt',0);
            $stock=array_column(Db::name('stock')->where($anywhere)->field('shopid as id,cid,num')->select(),'id');
            if (!$stock)return json(array('list'=>[]));
            $where['id']=array('in',implode(',',$stock));

            //仓库结束
            $info = Db::name('preproduct')->where($where)->limit($offset,6)->select();
            foreach($info as $k=>$v){
                $info[$k]['type']="成品";
                $info[$k]['storenum']=$this->getStore($v['id'],$cid);
            }
            $result = array("list"=>$info);
            return json($result);
        }
    }
    function add_store(){
        $userarr = explode("|",$this->uid);
        $userid = $this->user['userid'];
        if (!in_array($userid,$userarr))$this->error("您没有权限","/index/store/lists");
        if ($this->request->isPost()){
            $post = $_POST;
            if (Db::name("githouse")->where(array("gname"=>$post['gname']))->field('id')->find())$this->error("仓库名称已存在");
            $aInfo = Db::name("admin")->where(array("userid"=>$post['manger']))->field('mobile')->find();
            $post['mobile']=$aInfo['mobile'];
            $post['uname']=$this->user['userid'];
            $post['ctime']=time();
            Db::name('githouse')->insert($post);
            $this->success("操作成功");
        }
        $app = Factory::work($this->config);
        //$app->jssdk->setUrl("http://oa.fc62.com");
        $json = $app->jssdk->buildConfig(array('checkJsApi','selectEnterpriseContact','openEnterpriseChat','getLocation'),0,1);

        $dept = GetBaseInfo('Dept');
        $groupList = Db::name("auth_department")->field("id,name")->where('id','in',''.implode(',',$dept).'')->select();
        $ginfo = Db::name("githouse")->order('id desc')->field('id')->find();

        if ($ginfo){
            $bh="ck_".str_pad($ginfo['id']+1,4,"0",STR_PAD_LEFT);
        }else{
            $bh="ck_".str_pad(1,4,"0",STR_PAD_LEFT);
        }
        $this->view->assign("bh",$bh);

        $this->view->assign("groupList",$groupList);
        $this->view->assign("json",$json);
        return $this->view->fetch();

    }
    //工作台
    function store_list()
    {
        $userarr = explode("|",$this->uid);
        $userid = $this->user['userid'];
        if (!in_array($userid,$userarr))$this->error("您没有权限","/index/store/lists");


        if ($this->request->isAjax()){

            $where=[];
            $page = isset($_POST['counter']) ? intval($_POST['counter']) : 1;
            $title = $this->request->post('title');
            if (!empty($title)){
                $where['gname']=array('like',"%{$title}%");
            }
            $offset = 6*($page-1);
            $info = Db::name("githouse")->where($where)->limit($offset,6)->order("id desc")->select();
            foreach ($info as $k=>$v){
                $info[$k]['lxr']=$this->getPublisher($v['manger']);
            }
            return json(array("list"=>$info));



        }
        return $this->view->fetch();
    }
    function add_supplier(){
        $userarr = explode("|",$this->uid);
        $userid = $this->user['userid'];
        if (!in_array($userid,$userarr))$this->error("您没有权限","/index/store/lists");
        if ($this->request->isPost()) {
            $post = $_POST;
            if ($post['sname']=='' || $post['address']=='' || $post['lxr']==''){$this->error("必填项没有填写");}
            $id = Db::name("supplier")->insert($post,0,1);
            if ($id)$this->success("添加成功");
            $this->error("添加失败");
        }

        $supinfo = Db::name("supplier")->field('id')->order('id desc')->find();
        if ($supinfo){
            $bh="hdyj_".str_pad($supinfo['id']+1,4,"0",STR_PAD_LEFT);
        }else{
            $bh="hdyj_".str_pad(1,4,"0",STR_PAD_LEFT);
        }
        $this->view->assign("bh", $bh);

        return $this->view->fetch();

    }
    /*
    * 采购单列表
    *
    *
    * */
    public function lists(){
        $userarr = explode("|",$this->uid);
        $userid = $this->user['userid'];
        if (!in_array($userid,$userarr))$this->error("您没有权限","/index/store/lists");

        $db = new Purcha();

        //查询当前用户是否在列表中
        $userarr = explode("|",$this->uid);
        $userid = $this->user['userid'];
        $sql="";
        $end="";
        $status = $this->request->post("status");
        $title = $this->request->post("title");
        $supplier= $this->request->post("supplier");
        if (!empty($title)){
            $end.=" and order_id like '%{$title}%'";
        }
        if (!empty($supplier)){
            $end.=" and supplier={$supplier}";
        }
        $page = isset($_POST['counter']) ? intval($_POST['counter']) : 1;
        $tempArr=[];
        foreach ($this->statusArr as $v){
            $work=$this->workflow($this->followId,$v);
            $temp = explode(",",$work['auto_sponsor_ids']);
            if (in_array($userid,$temp)){
                $tempArr[]=$v;
            }
        }
//        if (!in_array($userid,$userarr) && !$tempArr){
//            $this->error("没有访问权限");
//        }

        if (!in_array($userid,$userarr)){
            if ($tempArr){
                $workData = $this->getWork();
                $strSta=implode(",",$tempArr);

                if (!empty($workData)){
                    $sql="id in({$workData}) or status in({$strSta})";
                }else{
                    $sql="status in({$strSta})";
                }
            }else{
                return null;
            }

        }else{

            //如果有审核权限
            if ($tempArr){

                $workData = $this->getWork();
                $strSta=implode(",",$tempArr);
                if (!empty($workData)){
                    if ($status!='' && $status==9){
                        $sql.="(publisher='{$userid}' and status in(9,8,7))  or status in({$strSta}) {$end}";
                    }else{
                        if ($status==null){
                            if ($workData!=''){
                                $sql.="(publisher='{$userid}' or id in({$workData}) or status in({$strSta})) {$end}";
                            }else{
                                $sql.="(publisher='{$userid}'  or status in({$strSta})) {$end}";

                            }


                        }else{
                            $sql.="publisher='{$userid}' and status={$status} {$end}";

                        }
                    }

                }else{

                    if ($status!=null && $status!='9') {
                        $sql .= "publisher='{$userid}' and status={$status} {$end}";
                    }else{
                        if ($status==null){
                            $sql.= "(publisher='{$userid}' or status in({$strSta})) {$end}";
                        }else{
                             $sql.= "(publisher='{$userid}' and status in(9,8,7)) or status in({$strSta}) {$end}";
                        }

                    }
                }
            }else{
                if ($status){
                    if ($status==9){
                        $sql.="publisher='{$userid}' and status in(9,8,7) {$end}";

                    }else{
                        $sql.="publisher='{$userid}' and status={$status} {$end}";

                    }
                }else{
                    $sql.="publisher='{$userid}' {$end}";
                }
                //没有审核权限


            }
        }

        if ($this->request->isAjax())
        {

            $page = isset($_POST['counter']) ? intval($_POST['counter']) : 1;
            $offset = 4*($page-1);
            $info = Db::name("purcha")->where($sql)->limit($offset,4)->order("id desc")->select();
            foreach ($info as $k=>$v){
                $info[$k]['supplier']=$this->getSup($v['supplier']);
                $info[$k]['createtime']=date("Y-m-d");
                $info[$k]['publisher']=$this->getPublisher($v['publisher']);
                $info[$k]['status']=$this->getStatus($v['status']);
            }
            $result = array("list"=>$info);
            return json($result);
        }

        $list = Db::name('supplier')->field("id,sname")->select();
        $this->view->assign("list", $list);
        $this->view->assign("userid", $userid);
        $this->view->assign("userarr", $userarr);
        return $this->view->fetch();

    }

    public function view($id)
    {
        $pdb = new Purcha();
        $info = Db::name('purcha')->where(array('id' => $id))->find();
        //检测是否是自己发布
        $userArrs=explode("|",$this->uid);

        if ($info['publisher']!=$this->user['userid'] || !in_array($this->user['userid'],$userArrs)){
            $bool=false;
            foreach ($this->statusArr as $v){
                $work=$this->workflow($this->followId,$v);
                $temp = explode(",",$work['auto_sponsor_ids']);
                if (in_array($this->user['userid'],$temp)){
                    $bool=true;
                }
            }
            if (!$bool)$this->error("没有权限");
        }
        $info['supplier'] = $this->getSup($info['supplier']);
        $info['status_text'] = $this->getStatus($info['status']);
        $info['username'] = $this->getPublisher($info['publisher']);
        $info['count'] = Db::name('purcha_data')->where(array('pur_id' => $id))->count();
        $list = Db::name('purcha_data')->field("shopid,num,price,actual")->where(array('pur_id' => $id))->select();
        $listarr = [];
        foreach ($list as $k => $v) {
            $listarr["flg_".$v['shopid']]=$v;
            $listarr["flg_".$v['shopid']]['cname'] = $this->getCname($v['shopid']);
            $listarr["flg_".$v['shopid']]['total'] = $v['num']-$v['actual'];

            $listarr["flg_".$v['shopid']]['storenum'] = $this->getStore($v['shopid']);;

        }
        //审批通过流程
        $worklist = Db::name("purcha_work")->where(array("pid" => $id))->select();

        if ($worklist) {
            foreach ($worklist as $k => $v) {

                $worklist[$k]['user'] = $this->getInfo($v['publisher']);
            }
        }
        if($pos = array_search($info['status'],$this->statusArr)!==false){
            $work = $this->workflow($this->followId,$info['status']);
            $userList = explode(",",$work['auto_sponsor_ids']);
            if ($userList){
                foreach ($userList as $k=>$v){
                   $array=[
                       'status'=>3,
                       "user"=>$this->getInfo($v),
                       'mark'=>''
                   ];
                   array_push($worklist,$array);

                }
            }

        }
        $this->view->assign('worklist',$worklist);
        $this->view->assign('jsList',json_encode($listarr));
        $this->view->assign('list',$listarr);
        $this->view->assign('info',$info);
       $this->view->assign('userid',$this->user['userid']);

        //权限处理
        $userArr=array();
        switch ($info['status']){
            case 9:
                $work2 = $this->workflow($this->followId,9);
                $userArr = explode(",",$work2['auto_sponsor_ids']);
                break;
            case 8:
                $work2 = $this->workflow($this->followId,8);
                $userArr = explode(",",$work2['auto_sponsor_ids']);
                break;
            case 7:
                $work2 = $this->workflow($this->followId,7);
                $userArr = explode(",",$work2['auto_sponsor_ids']);

                break;

            default:
                $userArr = explode(",",$info['publisher']);
                break;
        }

        $this->view->assign('userArr',$userArr);

        return $this->view->fetch();
    }
    /*
     * 工作流
     * 当前级别
     * */

    /*采购单添加*/
    public  function cgadd(){


            $userarr = explode("|",$this->uid);
            $userid = $this->user['userid'];
            if (!in_array($userid,$userarr))$this->error("您没有权限","/index/store/lists");

            if ($this->request->isPost() && isset($_POST['sub'])) {
            $pdb = new Purcha();
            $post = $_POST;
            $post['createtime']=strtotime($post['riqi']);
            $post['publisher']=$this->user['userid'];
            $shopList = $post['shopList'];
            $post['order_id']=$pdb->getOrderId();
            unset($post['riqi'],$post['shopList'],$post['sub']);
            Db::startTrans();
            $pid = $pdb->insert($post,0,1);
            if (!$pid) $this->error("订单号重复");
            if (!$shopList) $this->error("请添加商品");

            foreach ($shopList as $k=>$v){
                $check=Db::name('purcha_data')->insert(array('shopid'=>$v['id'],'num'=>$v['num'],'price'=>isset($v['price']) ? $v['price'] : 0,'pur_id'=>$pid));
                if (!$check)break;
            }
            if (!$check){
                Db::rollback();
                $this->error("添加失败");
            }else{
                Db::commit();
                if ($post['status']==9){

                    $work = $this->workflow($this->followId,9);
                    $person = str_replace(",","|",$work['auto_sponsor_ids']);
                    $this->sendText("待审核通知","<div class=\"gray\">单据日期：{$_POST['riqi']}</div> <div class=\"normal\">采购单号：{$post['order_id']}\n数量合计：{$post['total']}\n金额合计：{$post['total_money']}\n审核状态：待1级审核</div>",$this->host."index/store/view/id/".$pid,$person);
                }
                $this->setWork(Db::name("purcha")->where(array("id"=>$pid))->find(),$post['status']);
                $this->success("添加成功");
            }
        }else{


            $preCate = Db::name("halt_cate")->field('id,pid,name')->where(array("type"=>1,"pid"=>0))->order("id asc")->select();
            $firstCate=$preCate[0]['id'];
            $cate = Db::name("halt_cate")->field('id,pid,name')->where(array("pid"=>$firstCate))->order("id asc")->select();
            foreach ($cate as $k=>$v){
                $cate[$k]['cateArr']=Db::name("halt_cate")->field('id,pid,name')->where(array("pid"=>$v['id']))->order("id asc")->select();
            }

            $this->view->assign("preCate", $preCate);
            $this->view->assign("cate", $cate);

                /*供应商*/
            $sdb = new Supplier();
            $supInfo = collection($sdb->order('id desc')->select())->toArray();
            $sup = reset($supInfo);
            $pdb = new Purcha();
            $order_id = $pdb->getOrderId();
            $this->view->assign("order_id", $order_id);

            $this->view->assign("supInfo", $supInfo);
            $this->view->assign("sup", $sup);
            $this->view->assign("username", $this->user['username']);


            return $this->view->fetch();
        }


    }
    function getCate(){
        if (isset($_POST['cate1'])){
            $cate1 = intval($_POST['cate1']);
            $cate = Db::name("halt_cate")->field('id,pid,name')->where(array("pid"=>$cate1))->order("id asc")->select();

            if (!$cate)return json(array("code"=>0));
            $str='';
            foreach ($cate as $v){
                $str.='  <div class="cate_content_title">
                            <span class="h"></span><span>'.$v['name'].'</span><span class="h"></span>
                        </div>';
                $list = Db::name("halt_cate")->field('id,pid,name')->where(array("pid"=>$v['id']))->order("id asc")->select();
                $str.=' <table cellspacing="0" cellpadding="0">
                            <tr>';
                foreach ($list as $d){
                    $str.=' <td onclick="tdClick(this)" dataid="'.$d['id'].'">'.$d['name'].'</td>';
                }
                $str.='   </tr>
                        </table>';
            }
            return  json(array("code"=>1,'html'=>$str));
        }
    }
    protected function getWork($name="purcha_work"){
        $userid = $this->user['userid'];
        $info = Db::name($name)->field("pid")->where(array("publisher"=>$userid))->select();
        $array=[];
        foreach ($info as $v){
            if (!in_array($v['pid'],$array)){
                array_push($array,$v['pid']);
            }
        }
        if ($array){
            return implode(",",$array);
        }
        return '';
    }
    public function edit($id){

        $info = Db::name('purcha')->where(array('id'=>$id))->find();
        if ($info['publisher']!=$this->user['userid'])$this->error("您没有权限");
        if ($info['status']==10 || $info['status']==5){
            if ($this->request->isAjax()){
                $pdb = new Purcha();
                $post = $_POST;
                $post['createtime']=strtotime($post['riqi']);
                $shopList = $post['shopList'];
                unset($post['riqi'],$post['order_id'],$post['shopList'],$post['sub']);

                $pdb->save($post,array('id'=>$id));
                Db::name('purcha_data')->where(array("pur_id"=>$id))->delete();
                foreach ($shopList as $k=>$v){
                    Db::name('purcha_data')->insert(array('shopid'=>$v['id'],'num'=>$v['num'],'price'=>isset($v['price']) ? $v['price'] : 0,'pur_id'=>$id));

                }
                $this->setWork($info,$post['status']);

                if ($post['status']==9){
                    $work = $this->workflow($this->followId,9);
                    $person = str_replace(",","|",$work['auto_sponsor_ids']);
                    $this->sendText("待审核通知","<div class=\"gray\">单据日期：{$_POST['riqi']}</div> <div class=\"normal\">采购单号：{$info['order_id']}\n数量合计：{$post['total']}\n金额合计：{$post['total_money']}\n审核状态：待1级审核</div>",$this->host."index/store/view/id/".$id,$person);

                }

                $this->success("编辑成功","/index/store/view/id/".$id);
            }

            $this->view->assign("info",$info);
            $preCate = Db::name("halt_cate")->field('id,pid,name')->where(array("type"=>1,"pid"=>0))->order("id asc")->select();
            $firstCate=$preCate[0]['id'];
            $cate = Db::name("halt_cate")->field('id,pid,name')->where(array("pid"=>$firstCate))->order("id asc")->select();
            foreach ($cate as $k=>$v){
                $cate[$k]['cateArr']=Db::name("halt_cate")->field('id,pid,name')->where(array("pid"=>$v['id']))->order("id asc")->select();
            }

            $this->view->assign("preCate", $preCate);
            $this->view->assign("cate", $cate);

            /*供应商*/
            $sdb = new Supplier();
            $supInfo = collection($sdb->select())->toArray();

            $sup = $sdb->where(array("id"=>$info['supplier']))->find();

            $this->view->assign("supInfo", $supInfo);
            $this->view->assign("sup", $sup);
            $this->view->assign("username", $this->user['username']);
            $purList=Db::name('purcha_data')->field('shopid as id,num,price')->where(array("pur_id"=>$id))->select();
            foreach ($purList as $k=>$v){
                $purList[$k]['number']=$v['num'];
                $purList[$k]['cname']=$this->getCname($v['id']);
                $purList[$k]['storenum']=$this->getStore($v['id']);


            }


            $this->view->assign("purList", json_encode($purList));

            return $this->view->fetch();
        }else{
            $this->error("当前采购单不能编辑","/index/store/view/id/".$id);
        }

    }
    public function housing(){
        $id = $this->request->post("id");
        $shopList = $_POST['shopList'];
        if (!$id || !$shopList)$this->error("参数错误");
        $pdb = new Purcha();
        //$pbool =
        //if (!$pbool)DB::rollback();
        $houseDb = new In();//仓库表
        $order_id = $houseDb->getOrderId();
        $pur_data_db = new Data();//采购单数据表
        $stockDb = new \app\admin\model\Stock();//库存表
        $userid=$this->user['userid'];
        $cid=1;
        foreach ($shopList as $k=>$v){
            $shopid = $v['shopid'];
            $num = $v['total'];
            //入库记录
            $houseArr=array(
                'order_id'=>$order_id,
                'type'=>1,
                'shopid'=>$shopid,
                'num'=>$num,
                'cid'=>$cid,
                'pur_id'=>$id,
                'inputtime'=>time(),
                'publisher'=>$userid
            );
             $houseDb->insert($houseArr);

            $pur_data_db->where(array('pur_id'=>$id,"shopid"=>$shopid))->setInc('actual', $num);
            if ($stockDb->where(array('cid'=>$cid,"shopid"=>$shopid))->find()){
                $stockDb->where(array('cid'=>$cid,"shopid"=>$shopid))->setInc('num', $num);
            }else{
                Db::name('stock')->insert(array('cid'=>$cid,'num'=>$num,'shopid'=>$shopid));
            }

        }
        $pdb->save(array('status'=>2),array('id'=>$id));
        $this->success();
    }
    /*
   * 通过的一些其他操作
   * */
    public function oper(){
        $id = $this->request->post("id");
        $status = $this->request->post("status");
        if (!$id || $status=='')$this->error("参数错误");
        if (isset($_POST['mark']) && $_POST['mark']){
            $mark = trim($_POST['mark']);
        }
        $user = $this->user;
        $userid = $user['userid'];
        $info = Db::name('purcha')->where(array('id'=>$id))->find();
        if (in_array($status,array(4,1)))$this->error("此订单不能操作");

        if (in_array($status,$this->statusArr)){


            //检查审核权限
            $check = $this->workflow($this->followId,$status);

            $userArr = explode(",",$check['auto_sponsor_ids']);

            if (!in_array($userid,$userArr)){
                $this->error("您没有权限");
            }
        }



        switch ($status){
            case 10:
                //检查权限
                $pdb = new Purcha();
                $this->setWork($info,9);
                $work = $this->workflow($this->followId,9);
                $userList = str_replace(",","|",$work['auto_sponsor_ids']);

                $this->sendText("待审核通知","<div class=\"gray\">单据日期：".date("Y-m-d",$info['createtime'])."</div> <div class=\"normal\">采购单号：{$info['order_id']}\n数量合计：{$info['total']}\n金额合计：{$info['total_money']}\n审核状态：待".$work['step']."级审核</div>",$this->host."index/store/view/id/".$info['id'],$userList);

                $pdb->save(array("status"=>9),array('id'=>$id));
                $this->success("操作成功");
                break;
            case 9:
                $this->shenhe($id,$status);
            case 8:
                $this->shenhe($id,$status);
            case 7:
                $this->shenhe($id,$status);
                break;

            case 5:
                //订单作废
                $pdb = new Purcha();
                $pdb->save(array("status"=>4),array('id'=>$id));
                $this->setWork($info,4);

                $this->success("操作成功");
                break;
            case 2:
                $pdb = new Purcha();
                $this->setWork($info,1);

                $pdb->save(array("status"=>1),array('id'=>$id));
                $this->success("操作成功");
                break;
        }
    }

    /*
     * 驳回
     * */
    function reject(){
        $id = $this->request->post("id");
        $status = $this->request->post("status");
        $mark = $this->request->post("mark");

        if (!$id || $status=='')$this->error("参数错误");
        if ($mark=='')$this->error("请提交驳回意见");
        if (!in_array($status,$this->statusArr))$this->error("操作失败");
        if (in_array($status,array(4,1)))$this->error("此订单不能操作");
        $post = array_search($status, $this->statusArr);
        $work = $this->workflow($this->followId,$status);//查询当前是否是对应的用户名
        $user = $this->user;
        $userList = explode(",",$work['auto_sponsor_ids']);
        $userid = $user['userid'];
        if (!in_array($userid,$userList))$this->error("没有权限");
        $pdb = new Purcha();
        $pdb->save(array("status"=>5),array('id'=>$id));
        DB::name("purcha_work")->insert(array(
            "pid"=>$id,
            "inputtime"=>time(),
            "publisher"=>$userid,
            "mark"=>$mark,
            "status"=>2
        ));
        $info = Db::name('purcha')->where(array('id'=>$id))->find();
        $this->setWork($info,5);
        $this->sendText("驳回通知","订单号：{$info['order_id']}被驳回。\n原因：".$mark,$this->host."index/store/view/id/".$id,$info['publisher']);

        /*
         * 驳回通知
         * */
        $this->success("操作成功");



    }
    //审核通知
    protected function shenhe($id,$status){
        $pdb = new Purcha();
        if ($status!=7){
            $status-=1;
        }else{
            $status=3;
        }

        $userid=$this->user['userid'];
        $pdb->save(array("status"=>$status),array('id'=>$id));
        DB::name("purcha_work")->insert(array(
           "pid"=>$id,
           "inputtime"=>time(),
           "publisher"=>$userid,
           "mark"=>'',
           "status"=>1
        ));
        $info = Db::name('purcha')->where(array('id'=>$id))->find();
        $this->setWork($info,$status);

        if ($status==3){
            $this->sendText("审核成功通知","<div class=\"gray\">单号：{$info['order_id']}已经通过审核</div>",$this->host."index/store/view/id/".$info['id'],$info['publisher']);
        }else{
            $work = $this->workflow($this->followId,$status);
            $userList = str_replace(",","|",$work['auto_sponsor_ids']);
            $this->sendText("待审核通知","<div class=\"gray\">单据日期：".date("Y-m-d",$info['createtime'])."</div> <div class=\"normal\">采购单号：{$info['order_id']}\n数量合计：{$info['total']}\n金额合计：{$info['total_money']}\n审核状态：待".$work['step']."级审核</div>",$this->host."index/store/view/id/".$info['id'],$userList);

        }



        $this->success("操作成功");
    }
    //获取产品信息
    public function getProduct()
    {
        if ($this->request->isAjax()){
            $db = new Preproduct();
            $where=[];
            $where['type']=1;
            if (isset($_POST['pid']) && $_POST['pid'] > 0){
                $pid = intval($_POST['pid']);
                $where['classif']=$pid;
            }
            if (isset($_POST['title']) && $_POST['title']!=''){
                $title = $_POST['title'];
                $where['cname']=array('like',"%{$title}%");
            }
            $page = isset($_POST['counter']) ? intval($_POST['counter']) : 1;
            $offset = 6*($page-1);
            $info = collection($db->where($where)->limit($offset,6)->select())->toArray();
            foreach($info as $k=>$v){
                $info[$k]['storenum']=$this->getStore($v['id']);
            }
            $result = array("list"=>$info);
            return json($result);


         }
    }
    //库存查询
    public function stock(){
        if ($this->request->isAjax()){
            $where=[];
            $cid = $this->request->post("cid");
            $type = $this->request->post("type");

            $where['cid']=$cid;

            $page = isset($_POST['counter']) ? intval($_POST['counter']) : 1;
            $offset = 6*($page-1);
            if ($type!=null && $cid!=1){
                $where['type']=$type;
            }
            $where['num']=array('gt',0);
            $list = Db::name("stock")->where($where)->limit($offset,6)->select();
            foreach ($list as $k=>$v){
                $pInfo = Db::name("preproduct")->field("cname,b_n")->find($v['shopid']);
                $list[$k]['b_n']=$pInfo['b_n'];
                $list[$k]['cname']=$pInfo['cname'];
            }
            return json(array("list"=>$list));

        }
        $userid = $this->user['userid'];
        $sql = "find_in_set('$userid',docking)";
        //查询所在仓库信息
        $glist = Db::name('githouse')->where($sql)->field("id,gname")->select();
        if (!$glist)$this->error("没有对应的仓库所在对接人");
        $this->view->assign("glist", $glist);
        return $this->view->fetch();
    }
    //操作流程
    protected function setWork($info,$status){
        $id = $info["id"];
        if ($work = Db::name("workflow")->field("id")->where(array("tid"=>$id,"type"=>1))->find()){
            Db::name("workflow")->where(array("id"=>$work['id']))->update(array("status"=>$status,"uptime"=>time()));
        }else{
            Db::name("workflow")->insert(array("tid"=>$id,"status"=>$status,"order_id"=>$info['order_id'],"type"=>1,"inputtime"=>$info['createtime'],"uptime"=>time(), "userid"=>$this->user['userid']));

        }
        return true;

    }
    protected function getInfo($id){
        $info = DB::name('admin')->where(array("userid"=>$id))->field("avatar,username")->find();
        return $info;
    }
    protected function sendText($title,$desc,$url,$person){

        $content=array(
            "title"=>$title,
            "description" => $desc,
            "url" => $url,
            "btntxt"=>"查看"
        );
        pushMsgText($this->config,"textcard",$content,$person);
    }

    protected function workflow($id,$status){
        $list = DB::name("flow_process")->field("auto_sponsor_ids,range_user_ids")->where(array("flow_id"=>$id))->select();
        $array=array(
            "7"=>2,
            "8"=>1,
            "9"=>0,
        );
        if (!isset($array[$status])) return false;

        if($list[$array[$status]]['auto_sponsor_ids']==''){
            $list[$array[$status]]['auto_sponsor_ids']=$list[$array[$status]]['range_user_ids'];
        }

        return array_merge(array("step"=>$array[$status]+1), $list[$array[$status]]);


    }
    protected function getCname($id){
        $db = new Preproduct();

        $info = $db->where(array("id"=>$id))->find();
        if (!$info)return '';
        return $info['cname'];
    }
    protected function getStore($id,$cid=1){
        $db = new Stock();
        $info = $db->where(array('cid'=>$cid,'shopid'=>$id))->find();
        if (!$info)return 0;
        return $info['num'];
    }
    protected function getStatus($status){
        $str='';
        switch ($status){
            case "10":
                $str='<span class="num_right caogao">草稿</span>';
                break;
            case "9":
                $str='<span class="num_right shenpi">待1级审批</span>';
                break;
            case "8":
                $str='<span class="num_right shenpi">待2级审批</span>';
                break;
            case "7":
                $str='<span class="num_right shenpi">待3级审批</span>';
                break;
            case "5":
                $str='<span class="num_right shenpi">已通过</span>';
                break;

            case "-4":
                $str='<span class="num_right bohui">已驳回</span>';
                break;
            case "-1":
                $str='<span class="num_right finish">已作废</span>';
                break;
            case "-2":
                $str='<span class="num_right finish">申请变更</span>';
                break;
            case "-20":
                $str='<span class="num_right shenpi">变更成功</span>';
                break;
            case "-21":
                $str='<span class="num_right bohui">变更申请失败</span>';
                break;
            /*  case "5":
                  $str='<span class="num_right bohui">已驳回</span>';
                  break;
              case "-4":
                  $str='<span class="num_right finish">已作废</span>';
                  break;
              case "3":
                  $str='<span class="num_right pass">审批通过</span>';
                  break;
              case "2":
                  $str='<span class="num_right pass">部分入库</span>';
                  break;*/
            case "1":
                $str='<span class="num_right pass">已完成</span>';
                break;
        }
        return $str;
    }
    protected function getPublisher($id){
        $db = new Admin();
        $info = $db->where(array("userid"=>$id))->field('username')->find();
         if (!$info)return '';
         return $info['username'];
    }
    protected function getSup($id){
        $db = new Supplier();
        $info = $db->where(array('id'=>$id))->find();
        if (!$info)return '';
        return $info['sname'];
    }
    public function login(){
        $app = Factory::work($this->config);

        $token = $app->access_token->getToken();//获取企业微信token
        $code = $this->request->request('code');
        $url = "https://qyapi.weixin.qq.com/cgi-bin/user/getuserinfo?access_token={$token['access_token']}&code={$code}";
        $user = \fast\Http::get($url);
        if(!empty($user)) $user = json_decode($user,true);

        if($user['errcode'] == 0){
            if(isset($user['UserId'])){
                if(!$this->auth->IndexLogin($user['UserId'])){
                    $this->error(__('您的账户不存在，请联系管理员'));
                }else{
                    //print_r(\think\Session::get('admin')['userid']);die;


                    if(cookie("go_back")){

                        return redirect(cookie("go_back"));
                    }else{
                        return redirect($this->request->domain().'/index/store/index');
                    }
                    //return redirect($this->request->domain().'/index/store/lists');
                }
            }
        }else{
            return redirect($this->request->domain().'/index/store/oauth');
        }
    }


    public function oauth(){
        $url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=".$this->config['corp_id']."&redirect_uri=".$this->config['oauth']['callback']."&response_type=code&scope=".$this->config['oauth']['scopes']."&agentid=".$this->config['agent_id']."&state=STATE#wechat_redirect";
        return redirect($url);
    }

}
